package com.example.malltest.cart.service.impl;

import com.example.malltest.cart.entity.Cart;
import com.example.malltest.cart.entity.CartDTO;
import com.example.malltest.cart.mapper.CartMapper;
import com.example.malltest.cart.service.CartService;
import com.example.malltest.common.ServiceCode;
import com.example.malltest.common.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class CartServiceImpl implements CartService{

    @Autowired
    private CartMapper cartMapper;

    /**
     * 增加购物车
     * @param cartDTO
     */
    @Override
    public void add(CartDTO cartDTO){
        Cart cart1 = new Cart();
        cart1.setName(cartDTO.getName());
        cart1.setPrice(cartDTO.getPrice());
        cart1.setNum(cartDTO.getNum());
        Double totalPrice = cart1.getPrice()*cart1.getNum().doubleValue();
        cart1.setTotalPrice(totalPrice);
        cart1.setImage(cartDTO.getImage());
        cart1.setDateTime(cartDTO.getDateTime());
        int result = cartMapper.save(cart1);
        if(result<0){
            throw new ServiceException(ServiceCode.ERR_EXISTS,"增加失败！");
        }
    }

    /**
     * 获取购物车列表
     * @return
     */
    @Override
    public List<Cart> getList(){
        List<Cart> carts = cartMapper.getList();
        if(carts == null){
            throw new ServiceException(ServiceCode.ERR_EXISTS,"不存在购物车！");
        }
        return carts;
    }

    /**
     * 删除购物车
     * @param id
     */
    @Override
    public void delete(Integer id){
        Cart cart= cartMapper.getById(id);
        if(cart==null){
            throw new ServiceException(ServiceCode.ERR_EXISTS,"不存在购物车！");
        }
        int result = cartMapper.delete(id);
        if(result<0){
            throw new ServiceException(ServiceCode.ERR_EXISTS,"删除失败！");
        }
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void deleteBatch(List<Integer> ids){

          for(Integer id:ids){
             Cart cart= cartMapper.getById(id);
              if(cart==null){
                  throw new ServiceException(ServiceCode.ERR_EXISTS,"不存在购物车！");
              }
              int result = cartMapper.delete(id);
              if(result<0){
                  throw new ServiceException(ServiceCode.ERR_EXISTS,"删除失败！");
              }
          }
    }

}
